package com.smooth.mall.service.serviceImpl;


import com.smooth.mall.exception.SmoothMallException;
import com.smooth.mall.exception.SmoothMallExceptionEnum;
import com.smooth.mall.service.UserService;
import com.smooth.mall.model.dao.UserMapper;
import com.smooth.mall.model.pojo.User;
import com.smooth.mall.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User getUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(String username, String password) throws SmoothMallException {
        //查询用户名是否重名，不允许重名
        User result = userMapper.selectByName(username);
        if (result!=null){
        //业务层不进行异常处理，因此，需进行异常抛出
        //统一异常处理，创建异常处理类
            throw new SmoothMallException(SmoothMallExceptionEnum.NAME_EXISTED);
        }
        //写入数据库
        User user = new User();
        user.setUsername(username);
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        int count = userMapper.insertSelective(user);
        if(count==0){
            throw new SmoothMallException(SmoothMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String username, String password) throws SmoothMallException {
        String md5Password=null;
        try {
            md5Password = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println(md5Password);
        User user = userMapper.selectLogin(username, md5Password);
        //User user = userMapper.selectByPassword();
        if(user==null){
        //未找到用户，抛出异常
            throw new SmoothMallException(SmoothMallExceptionEnum.WRONG_PASSWORD);
        }
        //正常返回用户对象
        return user;
    }

    @Override
    public void updateInformation(User user) throws SmoothMallException {
        //更新个性签名
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 1) {
            throw new SmoothMallException(SmoothMallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdminRole(User user) {
    //1是普通用户，2是管理员
        return user.getRole().equals(2);
    }


}
